﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GP.Logic;
using GP.Logic.Model;
using System.Xml.Linq;
using System.Xml.XPath;

namespace WebForms.Doctor
{
    public partial class CitizenDetailedView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                DoctorService dr = new DoctorService();
                Citizen currentCitizen = dr.GetCitizen();
                string xmlPath = Request["path"];

                if (xmlPath == null)
                {
                    Response.Redirect("~/Doctor/CitizenView.aspx", false);
                    return;
                }
                XDocument doc = XDocument.Load(Server.MapPath(xmlPath.ToString()));
               // XDocument doc = XDocument.Load(Server.MapPath("~/test.xml"));

                #region citizen name
                string citizenID = doc.Root.XPathSelectElement(@"CitizenID").Value;
                hfCitizenID.Value = citizenID;

                CitizenService cs = new CitizenService();
               var citiName = cs.GetCitizen(long.Parse(citizenID));
               citizenName.Text = citiName.Name;

                #endregion

                UpdateBinding(citizenID, cs);


                var oximeters = doc.Root
                        .XPathSelectElements(@"VitalSigns/Signs/Oximeter")
                        .Select(a => new
                        {
                            saturationLevelVal = a.Element("SaturationLevel").Value,
                            heartRateVal = a.Element("HeartRate").Value,
                            dateVal = a.Parent.Parent.Element("VitalSignDate").Value
                        }).ToList();

                oxiGr.DataSource = oximeters;
                oxiGr.DataBind();

                var bp = doc.Root
                    .XPathSelectElements(@"VitalSigns/Signs/BloodPressure")
                    .Select(a => new
                    {
                        systolicVal = a.Element("Systolic").Value,
                        diastolicVal = a.Element("Diastolic").Value,
                        hearRateVal = a.Element("HeartRate").Value,
                        dateVal = a.Parent.Parent.Element("VitalSignDate").Value
                    }).ToList();

                bpGrid.DataSource = bp;
                bpGrid.DataBind();

                var ecgs = doc.Root
                    .XPathSelectElements(@"VitalSigns/Signs/ECG/ECGValues")
                    .Select(a => new
                    {
                        Values = string.Join("<br />", a.Elements("value").Select(x => x.Value).ToArray()),
                        dateVal = a.Parent.Parent.Parent.Element("VitalSignDate").Value

                    }).ToList();

                ecgsGr.DataSource = ecgs;
                ecgsGr.DataBind();

                var weight = doc.Root
                    .XPathSelectElements(@"VitalSigns/Signs/Weigth")
                    .Select(a => new
                    {
                        weightVal = a.Element("WeigthInGrams").Value,
                        dateVal = a.Parent.Parent.Element("VitalSignDate").Value
                    }).ToList();

                weightGrid.DataSource = weight;
                weightGrid.DataBind();


            }
        }

        private void UpdateBinding(string citizenID, CitizenService cs)
        {
            ddlEvents.DataSource = cs.GetEvents(long.Parse(citizenID));
            ddlEvents.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int eventID = int.Parse(ddlEvents.SelectedValue);
            #region Oximeter
            

            foreach(GridViewRow row in oxiGr.Rows)
            {
                var checkBox = row.Cells[4].FindControl("CheckBox1") as CheckBox; //cast control as checkbox
                if (checkBox == null)
                {
                    return;
                }

                if (checkBox.Checked)
                {
                    String heartRate = row.Cells[1].Text;
                    String saturration = row.Cells[2].Text;
                    
                    Note oxiNote = new Note();
                    oxiNote.Description = GetText(row.Cells[3]);

                    Oximeter oxi = new Oximeter();
                    oxi.Type = "O";

                    oxi.HeartRate = int.Parse(heartRate);
                    oxi.SaturationLevel = int.Parse(saturration);
                    oxi.Notes.Add(oxiNote);
                    oxi.EventId = eventID;
                    

                    GpContext gContext = new GpContext();
                    gContext.Oximeters.Add(oxi);
                    gContext.SaveChanges();
                }
            }
            #endregion

            #region Weight
                        foreach(GridViewRow row in weightGrid.Rows)
            {
                var checkBox = row.Cells[3].FindControl("CheckBox1") as CheckBox; //cast control as checkbox
                if (checkBox == null)
                {
                    return;
                }

                if (checkBox.Checked)
                {
                    String  weightVal= row.Cells[1].Text;
                    Note weightNote = new Note();
                    weightNote.Description = GetText(row.Cells[2]);

                    Weight weight = new Weight();
                    weight.Type = "W";
                    weight.WeightInGrams = int.Parse(weightVal);

                    weight.Notes.Add(weightNote);
                    weight.EventId = eventID;

                    GpContext gContext = new GpContext();
                    gContext.Weights.Add(weight);
                    gContext.SaveChanges();
                }
            }
            #endregion

            #region BP
                        foreach(GridViewRow row in bpGrid.Rows)
            {
                var checkBox = row.Cells[5].FindControl("CheckBox1") as CheckBox; //cast control as checkbox
                if (checkBox == null)
                {
                    return;
                }

                if (checkBox.Checked)
                {
                    String systolicVal = row.Cells[1].Text;
                    String diastolicVal = row.Cells[2].Text;
                    String hearRateVal = row.Cells[3].Text;
                    Note comment = new Note();
                    comment.Description = GetText(row.Cells[4]);

                    BloodPressure bp = new BloodPressure();
                    bp.Type = "B";
                    
                    bp.Systolic = int.Parse(systolicVal);
                    bp.Diastolic = int.Parse(diastolicVal);
                    bp.HeartRate = int.Parse(hearRateVal);
                    bp.Notes.Add(comment);
                    bp.EventId = eventID;
                    
                    GpContext gContext = new GpContext();
                    gContext.BloodPressures.Add(bp);
                    gContext.SaveChanges();
                }
            }
            #endregion

            #region ECG
            foreach (GridViewRow row in ecgsGr.Rows)
            {
                var checkBox = row.Cells[3].FindControl("CheckBox1") as CheckBox;
                if (checkBox == null)
                    return;

                if (checkBox.Checked)
                {
                    string[] strings = row.Cells[1].Text.Split(new[] { "<br />" }, StringSplitOptions.RemoveEmptyEntries);
                    Note ecgNote = new Note();
                    ecgNote.Description = GetText(row.Cells[2]);
                   

                    GpContext context = new GpContext();


                    // var enumerable = strings.Select(a =>  double.Parse(a, new CultureInfo("en-US"))).ToList();

                    ECG ecg = new ECG();
                   // ecg.CitizenId = 1;
                    ecg.EventId = eventID;
                    ecg.Type = "E";
                    ecg.Notes.Add(ecgNote);

                    char i = 'A';
                    foreach (var s in strings)
                    {
                        ECGValue value = new ECGValue();
                        value.Value = s;
                        value.ECGID = new string(i, 1);
                        i++;
                        ecg.Values.Add(value);
                    }

                    context.Ecgs.Add(ecg);
                    context.SaveChanges();
                }
            }
            #endregion
        }

        private string GetText(TableCell tableCell)
        {
            foreach (var control in tableCell.Controls)
            {
                var textBox = control as TextBox;
                if(textBox == null)
                    continue;

                return textBox.Text;
            }

            return "";
        }

        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            CitizenService citizenService = new CitizenService();

            long citizenId = long.Parse(hfCitizenID.Value);

            Event @event = citizenService.CreateEvent(citizenId, txtEventType.Text, txtSubject.Text, txtMainText.Text,
                                                      txtEquipment.Text);


            UpdateBinding(citizenId.ToString(), citizenService);
            // citizenService.CreateEvent()
        }
    }
}